let template = []
let save_excel =null

function init_data(){
    let save_path = "/sdcard//rpa/result/小红书数据采集" + time.date() + ".xls"
    if(files.exists(save_path)){
        files.remove(save_path)
    }
    save_excel = excel.open(save_path,time.date())
    excel.appendRow(save_excel,["发布时间","标题","文案","点赞数","收藏数","评论数","达人名","达人粉丝量","话题tag"])
    excel.syncDisk(save_excel)
}

function resetDevice() {
    console.log('>>>准备初始化环境<<<')
    automator.home() // 点击home按键
    sleep(500)
    automator.recents() // 展开最近任务
    //抬起设备最近任务
    selector().id('clearAnimView').findOne().click()
    console.log('>>>环境初始化完成<<<')

}


function waitForActivityNameOrError(activeName, timeout) {
    for (let i = 0; i < timeout; i++) {
        if (app.getCurrentActivityName() === activeName) {
            return true
        }
        sleep(1000)
    }
    return false
}


function getRealDate(dateStr) {
    // 根据小红书采集到的数据时间获取真实时间
    dateStr = dateStr.replace(/\s+/g, '')
    dateStr = dateStr.replace(/编辑于/, '')
    if (/^\d+-\d+-\d+$/.test(dateStr)) {
        return dateStr
    } else if (/^\d+-\d+$/.test(dateStr)) {
        return '2023-' + dateStr
    } else if (/^\d+-\d+/.test(dateStr)) {
        return '2023-' + dateStr.replace(/^.*(\d\d-\d\d).*$/, '$1')
    } else if (/今天/.test(dateStr)) {
        return time.date()
    } else if (/昨天/.test(dateStr)) {
        return time.yesterday()
    }
}



function searcch_by_xhs(serach_key){
    selector().id('gbj').click()
    selector().id('ebg').setText(serach_key)
    selector().id('ebl').click()
}


function get_data_for_fill(real_date){ // 从视频内获取数据
    let title = selector().id('f3c').findOne(200).text()  //标题
    let noteText = selector().id('noteContentText').findOne()
    let copywriting = ""
    if (noteText.text().indexOf('展开全文') !== -1) {
        automator.click(noteText.bounds().right - 25, noteText.bounds().bottom - 25)
        try{
            copywriting = selector().id('f3x').findOne(200).findOne(selector().id('f3w')).text()
        }catch (e) {
            console.warn("-------弹出全文窗口-------")
            copywriting = selector().id('f3w').findOne(200).text()
            selector().id('ao0').findOne(200).click()
            sleep(500)
        }
    }else{
        copywriting = noteText.text()
    }
    //console.log(copywriting)
    let like = selector().id("eiy").findOne(200).text() .indexOf("点赞") != -1 ? '0' : selector().id('eiy').findOne(200).text()  // 点赞
    let collect = selector().id('eit').findOne(200).text() .indexOf("收藏") != -1 ? '0' : selector().id('eit').findOne(200).text()  // 收藏
    let comment = selector().id('eiv').findOne(200).text() .indexOf("评论") != -1 ? '0' : selector().id('eiv').findOne(200).text()  // 评论
    // let nickNameSelector = selector().id('matrixNickNameView').findOne(20);
    // automator.click(nickNameSelector.centerX(), nickNameSelector.centerY()) // 通过坐标点击
    selector().id('i2w').findOne(200).click()
    sleep(1000)
    selector().id('fq2').waitFor(20) // 等待跳转
    let nick_name = selector().id('fq2').findOne(200).text() 
    let fans_count = selector().id("bog").findOne(200).text() .indexOf("万") != 1 ? parseFloat(selector().id("bog").findOne(200).text() .match(/\d+/)[0])*1000 : Number(selector().id("bog").findOne(200).text() )
    let target = ""
    //console.log(copywriting.match(/#\S+/g))
    try{
        target = copywriting.match(/#\S+/g).join(",")
    }catch(e){
        target = ""
    }
    automator.back()
    excel.appendRow(save_excel,[real_date,title,copywriting,like,collect,comment,nick_name,fans_count,target])
    excel.syncDisk(save_excel)
    sleep(1000)
    automator.back()
}


function get_data_for_note(real_date){
    selector().id('f54').waitFor(20)
    let title = ""  // 标题
    try{
        title = tselector().id('f54').findOne(200).text()
    }catch(e){
        console.warn("傻逼吧，怎么会有人发小红书不写标题的啊")
        title = ""
    }
    let copywriting = selector().id('cy1').findOne(200).text()  // 文案
    let like = selector().id('f4d').findOne(200).text() .indexOf("点赞") != -1 ? '0' : selector().id('f4d').findOne(200).text()  // 点赞
    let collect = selector().id('f2r').findOne(200).text() .indexOf("收藏") != -1 ? '0' : selector().id('f2r').findOne(200).text()  // 收藏
    let comment = selector().id('f30').findOne(200).text() .indexOf("评论") != -1 ? '0' : selector().id('f30').findOne(200).text()  // 评论
    let click_center = selector().id('sv').findOne(200)
    console.hide()
    sleep(500)
    automator.click(click_center.centerX(),click_center.centerY())
    sleep(500)
    console.show()
    selector().id('fq2').waitFor(20) // 等待跳转
    let nick_name = selector().id('fq2').findOne(200).text() 
    let fans_count = selector().id("bog").findOne(200).text() .indexOf("万") != 1 ? parseFloat(selector().id("bog").findOne(200).text() .match(/\d+/)[0])*1000 : Number(selector().id("bog").findOne(200).text() )
    let target = ""
    //console.log(copywriting.match(/#\S+/g))
    try{
        target = copywriting.match(/#\S+/g).join(",")
    }catch(e){
        target = ""
    }
    automator.back()
    excel.appendRow(save_excel,[real_date,title,copywriting,like,collect,comment,nick_name,fans_count,target])
    excel.syncDisk(save_excel)
    sleep(1000)
    automator.back()
}


function get_data_for_xhs(real_date){
    // 获取activity来导航到不同方法
    console.log(" ---- 开始获取数据 ----")
    let actity_name = app.getCurrentActivityName()
    if(actity_name.indexOf('DetailFeedActivity') != -1){
        get_data_for_fill(real_date)
        
    }else if(actity_name.indexOf('NoteDetailActivity') != -1){
        get_data_for_note(real_date)
    }else{
        throw("异常!!!!")
    }
}


function loop_serach_ret(){
    let d1m_list = selector().id('d1m').find()
    for(let i=0;i<d1m_list.size();i++){
        let day_list = []
        if(/天前/.test(d1m_list[i].text() )){
            // 天前存在
            day_list = time.date().split("-")
        }else{

            day_list = getRealDate(d1m_list[i].text() ).split("-")     
        }
        let day_number = Number(day_list[0]) * 12 * 30 + Number(day_list[1]) * 30 + Number(day_list[2])
        if(728438 < day_number && day_number < 728480 ){
            let nick_name = d1m_list[i].prev().text()  
            let po_text = d1m_list[i].parent().parent().prev().text() 
            let temp_str = day_number+nick_name+po_text
            if(template.indexOf(temp_str) != -1){
                continue
            }else{
                template.push(temp_str)
                console.log("计数器:" + template.length + "条")
                d1m_list[i].parent().parent().parent().parent().click() // 进入小红书内部
                sleep(2000)
                get_data_for_xhs(getRealDate(d1m_list[i].text() ))
                sleep(1500)
            }
        }

    }
}


function stopAlertMessage(title, message) {
    dialogs.alert(title, message);
    stop(message);
}



// 程序开始
console.show()
console.clear()
console.log('>>>开始执行小红书数据采集流程<<<')
resetDevice()
init_data()
// 启动app
app.launchAppVersionOrStop("小红书",'7.93.0')
searcch_by_xhs("阿迪达斯")
sleep(2000)
while(true){
    loop_serach_ret()
    if(template.length >= 10){
        break
    }
    automator.swipeDown()
}
cloudFile.upload("小红书数据采集" + time.date() + ".xls","/sdcard/rpa/result/小红书数据采集" + time.date() + ".xls")
stopAlertMessage("流程执行完成","流程执行完成，相关数据请在commander查看!")